package com.bbbug.coree.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbbug.coree.service.RooominfoService;
import com.bbbug.coree.entity.Roominfo;
import com.bbbug.coree.utils.SpringUtils;
import com.bbbug.coree.websocketservice.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.yeauty.pojo.Session;

import javax.annotation.PostConstruct;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SongTask {
    public static ConcurrentHashMap<String, Long> channelhome = new ConcurrentHashMap();
    private final RedisTemplate redisTemplate = SpringUtils.getBean("redistemp");
    RooominfoService rooominfoService=SpringUtils.getBean(RooominfoService.class);
    private static ConcurrentHashMap<String, ConcurrentHashMap<String, Session>> chatmap = core.CHATMAP;
    @Scheduled(fixedRate = 30000)
    private void songTask() {
        for (String name : chatmap.keySet()) {
            if (redisTemplate.opsForList().size(name) >= 2) {
                Object index = redisTemplate.opsForList().index(name, 1);
                JSONObject jtp = JSON.parseObject(index.toString());
                Long since = System.currentTimeMillis() / 1000;
                Long second = since % 60, min = since / 60 % 60, hour = (since / 3600 + 8) % 24;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("time", hour + ":" + min + ":" + second);
                jsonObject.put("type", "preload");
                jsonObject.put("by", "timer");
                jsonObject.put("url", "/api/song/playurl?mid=" + jtp.getJSONObject("song").get("mid"));
                SendForALL(name, jsonObject.toJSONString());
            }
        }
    }

    @Scheduled(fixedRate = 1000)
    void delandsend() {
        ListOperations listOperations = redisTemplate.opsForList();
        for (String name : chatmap.keySet()) {
            if (channelhome.get(name) == null) {
                channelhome.put(name, System.currentTimeMillis());
            }
            Roominfo roominfo = rooominfoService.queryById(Integer.parseInt(name));
            if(roominfo.getRoom_type()==0) {
                continue;
            }
            Long len = listOperations.size(name);
            if (len > 0) {
                JSONObject jtp = JSON.parseObject(listOperations.index(name, 0).toString());
                Long songlength = Long.parseLong(jtp.getJSONObject("song").get("length").toString());
                if (System.currentTimeMillis() >= (channelhome.get(name) + songlength * 1000)) {
                    if(roominfo.getRoom_playone()!=null&&roominfo.getRoom_playone()==1){
                        listOperations.leftPop(name);
                        jtp.put("since", System.currentTimeMillis() / 1000);
                        jtp.put("by","playone");
                        listOperations.leftPush(name,jtp.toJSONString());
                    }else{
                        listOperations.leftPop(name);
                        len--;
                    }
                    if (len > 0) {
                        JSONObject jnow = JSON.parseObject(listOperations.index(name, 0).toString());
                        channelhome.put(name, System.currentTimeMillis());
                        jnow.put("since", System.currentTimeMillis() / 1000);
                        jnow.put("type", "playSong");
                        jtp.put("count",len-1);
                        SendForALL(name, jnow.toJSONString());
                    }
                }
            }
            if (len == 0&&rooominfoService.getroomneedsbronbotbyid(Integer.parseInt(name)).getRoom_robot()==0) {
                BoundSetOperations history = redisTemplate.boundSetOps("history");
                if (history!=null&&history.size()>0) {
                    Object index = history.randomMember();
                    JSONObject jtp = JSON.parseObject(index.toString());
                    jtp.put("type", "playSong");
                    jtp.put("count",len);
                    channelhome.put(name, System.currentTimeMillis());
                    jtp.put("since", System.currentTimeMillis() / 1000);
                    jtp.put("end",  (System.currentTimeMillis()+jtp.getJSONObject("song").getLong("length")*1000)/ 1000);
                    JSONObject jsonObject =new JSONObject();
                    jsonObject.put("user_name", "Robot");
                    jsonObject.put("user_id", 1);
                    jtp.put("user", jsonObject);
                    jtp.put("by", "randomMember");
                    SendForALL(name, jtp.toJSONString());
                    listOperations.rightPush(name, jtp.toJSONString());
                }
            }
        }
    }


    boolean SendForALL(String room_id,String message) {
        ConcurrentHashMap<String, Session> stringSessionConcurrentHashMap = core.CHATMAP.get(room_id);
        if (stringSessionConcurrentHashMap == null) {
            return false;
        }
        for (Session value : stringSessionConcurrentHashMap.values()) {
            value.sendText(message);
        }
        return true;
    }
}